/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.formmetadata.metadataanalysis;

import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.web.common.environment.ExecuteEnvironment;
import com.inspur.edp.web.common.utility.StringUtility;
import com.inspur.edp.web.formmetadata.metadata.formdom.FormDOM;
import com.inspur.edp.web.formmetadata.metadatamanager.StateMachineMetadataManager;

import java.util.HashMap;

/**
 * 状态机的解析
 */
public class StateMachineAnalysis {
    /**
     * 解析状态机元数据
     */
    public static void resolveStateMachine(FormDOM json, String metaDataFileName, String targetStoragePath, String webDevPath,
                                           String projectPath, ExecuteEnvironment executeEnvironment,
                                           boolean isUpdradeTool) {
        // Get StateMachine Metadata, and Save StateMachine
        if (json.getModule() != null && json.getModule().getStateMachines() != null && json.getModule().getStateMachines().size() > 0) {
            StateMachineMetadataManager smManager = new StateMachineMetadataManager(executeEnvironment, isUpdradeTool);
            StringBuilder stateMachines = new StringBuilder();
            stateMachines.append("{");
            int index = 0;
            for (HashMap<String, Object> o : json.getModule().getStateMachines()) {
                if (index > 0) {
                    stateMachines.append(",");
                }
                String uri = o.get("uri").toString();
                GspMetadata obj = smManager.getStateMachine(uri, StringUtility.getOrDefault(o.get("code"), ""), StringUtility.getOrDefault(o.get("name"), ""), StringUtility.getOrDefault(o.get("nameSpace"), ""));
                String sm_json = smManager.serialize(obj.getContent());
                String idStr = o.get("id").toString();
                stateMachines.append("\"").append(idStr).append("\":");
                stateMachines.append(sm_json);
                index += 1;
            }
            stateMachines.append("}");

            // Save StateMachine
            smManager.saveMetadataFile(targetStoragePath, String.format("%1$s.sm.json", metaDataFileName.toLowerCase()), stateMachines.toString());
        }
    }
}
